package cn.iocoder.yudao.module.handguard.service.wealthrecord;

import cn.iocoder.yudao.module.handguard.controller.admin.wealthrecords.vo.SettingRateVO;
import cn.iocoder.yudao.module.handguard.controller.app.applicationrecord.vo.ApplyRecordDO;
import cn.iocoder.yudao.module.handguard.dal.mysql.housingresource.HousingResourceMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import cn.iocoder.yudao.module.handguard.controller.app.wealthrecord.vo.*;
import cn.iocoder.yudao.module.handguard.dal.dataobject.wealthrecord.WealthRecordDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.handguard.convert.wealthrecord.WealthRecordConvert;
import cn.iocoder.yudao.module.handguard.dal.mysql.wealthrecord.WealthRecordMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.handguard.enums.ErrorCodeConstants.*;

/**
 * 用户-财富值明细记录 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class WealthRecordServiceImpl implements WealthRecordService {

    @Resource
    private WealthRecordMapper wealthRecordMapper;

    @Resource
    private HousingResourceMapper housingResourceMapper;

    @Override
    public Long createWealthRecord(WealthRecordCreateReqVO createReqVO) {
        // 插入
        WealthRecordDO wealthRecord = WealthRecordConvert.INSTANCE.convert(createReqVO);
        wealthRecordMapper.insert(wealthRecord);
        // 返回
        return wealthRecord.getId();
    }

    @Override
    public void updateWealthRecord(WealthRecordUpdateReqVO updateReqVO) {
        // 校验存在
        validateWealthRecordExists(updateReqVO.getId());
        // 更新
        WealthRecordDO updateObj = WealthRecordConvert.INSTANCE.convert(updateReqVO);
        wealthRecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteWealthRecord(Long id) {
        // 校验存在
        validateWealthRecordExists(id);
        // 删除
        wealthRecordMapper.deleteById(id);
    }

    private void validateWealthRecordExists(Long id) {
        if (wealthRecordMapper.selectById(id) == null) {
            throw exception(WEALTH_RECORD_NOT_EXISTS);
        }
    }

    @Override
    public WealthRecordDO getWealthRecord(Long id) {
        return wealthRecordMapper.selectById(id);
    }

    @Override
    public List<WealthRecordDO> getWealthRecordList(Long userId) {
        LambdaQueryWrapper<WealthRecordDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WealthRecordDO::getUserId,userId);
        queryWrapper.orderByDesc(WealthRecordDO::getCreateTime);
        return wealthRecordMapper.selectList(queryWrapper);
    }

    @Override
    public PageResult<WealthRecordDO> getWealthRecordPage(WealthRecordPageReqVO pageReqVO) {
        return wealthRecordMapper.selectPage(pageReqVO);
    }

    @Override
    public List<WealthRecordDO> getWealthRecordList(WealthRecordExportReqVO exportReqVO) {
        return wealthRecordMapper.selectList(exportReqVO);
    }

    @Override
    public PageResult<UserWealthRecordRespVO> getUserWealthRecordPage(WealthRecordPageReqsVO pageVO) {
        PageResult<UserWealthRecordRespVO> pageResult = new PageResult<>();
        int firstIndex = (pageVO.getPageNo() - 1) * pageVO.getPageSize();
        pageVO.setPageNo(firstIndex);
        Long count = wealthRecordMapper.findByPageCount(pageVO);
        List<UserWealthRecordRespVO> respVOList = wealthRecordMapper.findByPage(pageVO);
        pageResult.setTotal(count);
        pageResult.setList(respVOList);
        return pageResult;
    }

    @Override
    public WealthRespVO getWealthByUserId(Long userId) {
        return wealthRecordMapper.getWealthByUserId(userId);
    }

    @Override
    @Transactional
    public String updateMyWealth(WealthUpdateReqVO updateReqVO) {
        String msg = "操作成功";
        if (updateReqVO.getNewWealthValue().compareTo(BigDecimal.ZERO) < 0){
            msg = "操作失败，非法操作！";
            return msg;
        }
        WealthRespVO respVO =  getWealthByUserId(updateReqVO.getId());
        if (respVO!=null){
            BigDecimal wealth = new BigDecimal(BigInteger.ZERO);
            //当前
            BigDecimal nowWealth = respVO.getWealthValue();
            //扣除值
            BigDecimal wealthValue = updateReqVO.getNewWealthValue();

            boolean canSubtract = areEnoughToSubtract(nowWealth, wealthValue);
            if (canSubtract){
                wealth = nowWealth.subtract(wealthValue);
                wealthRecordMapper.updateMyWealth(updateReqVO.getId(),wealth);
                //插入纪录
                WealthRecordDO recordDO = new WealthRecordDO();
                recordDO.setWealthValue(wealthValue);
                recordDO.setUserId(updateReqVO.getId());
                recordDO.setIOrDecrease("0");
                recordDO.setRemark(updateReqVO.getRemark());
                wealthRecordMapper.insert(recordDO);
                return msg;
            }else {
                return "操作失败，当前财富值不足以扣除！";
            }
        }
        return "操作失败";
    }

    @Override
    public String updateRate(SettingRateVO rateVO) {
        wealthRecordMapper.updateRate(rateVO.getRateValue(),rateVO.getKey());
        return "操作成功";
    }

    @Override
    public SettingRateVO getRateValue(String key) {
        String values = housingResourceMapper.getSslURL(key);
        SettingRateVO rateVO = new SettingRateVO();
        rateVO.setRateValue(new BigDecimal(values));
        return rateVO;
    }

    public static boolean areEnoughToSubtract(BigDecimal a, BigDecimal b) {
        BigDecimal sum = a.subtract(b);
        if (sum.compareTo(BigDecimal.ZERO)< 0){
            return false;
        }else {
            return true;
        }
    }

}
